<template>
  <el-dialog
          model-value="dialogVisible"
          :title="dialogTitle"
          :width="width"
          align-center
          @close="handleClose"
  >

    <div style="height: 250px">
      <el-form ref="formRef"
               :model="form"
               :rules="rules"
               label-width="100px"
               v-if="multiSelectData.singleMulti==='single'"
      >
        <el-form-item label="资产名称" prop="zcmc">
          <el-input v-model="form.zcmc"/>
        </el-form-item>
        <el-form-item label="资产类别" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择...">
            <el-option
                    v-for="item in selectAssetTypeOptionData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资产型号" prop="zcxh">
          <el-input v-model="form.zcxh"/>
        </el-form-item>
        <el-form-item label="生厂厂家" prop="sccj">
          <el-input v-model="form.sccj"/>
        </el-form-item>
        <el-form-item label="库存数量" prop="kcsl">
          <el-input v-model="form.kcsl" type="number"/>
        </el-form-item>
      </el-form>

      <el-table id="assets"
                ref="tableDataRef"
                :data="tableData"
                border
                height="280"
                style="width: 100%;"
                :cell-style="{textAlign: 'center'}"
                :header-cell-style="{textAlign: 'center'}"
                v-if="multiSelectData.singleMulti==='multi'"
                @cell-click="handleCellClick"
      >
        <el-table-column prop="zcmc" label="资产名称">
          <template #default="scope">
            <el-input size="small" class="item_input" v-model="scope.row.zcmc" placeholder="请输入内容"/>
            <span class="item_txt">{{ scope.row.zcmc }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="typeId" label="资产类别" width="200">
          <template class="item" #default="scope">
            <el-select size="small" class="item_input" v-model="scope.row.typeId" placeholder="请选择...">
              <el-option
                      v-for="item in selectAssetTypeOptionData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
              />
            </el-select>
            <span class="item_txt">{{ formatTypeId(scope.row.typeId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="zcxh" label="资产型号">
          <template class="item" #default="scope">
            <el-input size="small" class="item_input" v-model="scope.row.zcxh" placeholder="请输入内容"/>
            <span class="item_txt">{{ scope.row.zcxh }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sccj" label="生厂厂家">
          <template class="item" #default="scope">
            <el-input size="small" class="item_input" v-model="scope.row.sccj" placeholder="请输入内容"/>
            <span class="item_txt">{{ scope.row.sccj }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="kcsl" label="库存数量">
          <template class="item" #default="scope">
            <el-input size="small" class="item_input" v-model="scope.row.kcsl" placeholder="请输入内容"/>
            <span class="item_txt">{{ scope.row.kcsl }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="save(scope.row)" type="primary">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from "vue";
import request from "@/util/request";
import { ElMessage } from 'element-plus';

const width = ref("");

/**
 *对话框属性初始化
 */
const props = defineProps(
        {
          ids: {
            type: Array,
            default: [],
            required: true
          },
          dialogTitle: {
            type: String,
            default: '',
            required: true
          },
          dialogVisible: {
            type: Boolean,
            default: false,
            required: true
          }
        }
)

/**
 * 多选判断属性
 */
const multiSelectData = ref({
  singleMulti: "",
  id: -1,
  idsArray: [],
})

/**
 * 监听窗口打开的变化
 */
watch(
        () => props.dialogVisible,
        () => {
          if (props.ids.length > 0 && props.ids.length === 1) {
            width.value = "30%"
            props.ids.forEach((item) => {
              multiSelectData.value.id = item
            })
            multiSelectData.value.singleMulti = "single";
            initFormData(multiSelectData.value.id);
          } else if (props.ids.length > 1) {
            width.value = "50%"
            props.ids.forEach((item) => {
              multiSelectData.value.idsArray.push(item)
            })
            multiSelectData.value.singleMulti = "multi";
            initTableData(multiSelectData.value.idsArray)
          } else {
            form.value = {
              id: -1,
              zcmc: "",
              typeId: "",
              zcxh: "",
              sccj: "",
              kcsl: "",
            }
          }
        }
)

/**
 *初始化表单数据
 */
const form = ref({
  id: -1,
  zcmc: "",
  typeId: "",
  zcxh: "",
  sccj: "",
  kcsl: "",
})

/**
 * 表单校验规则
 */
const rules = ref({
  zcmc: [{required: true, trigger: "blur", message: "请输入资产名称"}],
  typeId: [{required: true, trigger: "blur", message: "请选择资产类别"}],
  zcxh: [{required: true, trigger: "blur", message: "请输入资产型号"}],
  sccj: [{required: true, trigger: "blur", message: "请输入生产厂家"}],
  kcsl: [{required: true, trigger: "blur", message: "请输入库存数量"}],
})

/**
 * 定义资产类别数组
 */
const selectAssetTypeOptionData = ref([]);

/**
 * 获得所有的资产类别信息
 */
const getAssetType = async () => {
  const res = await request.get("assetType/list");
  console.log(res.data.assetTypeList);
  selectAssetTypeOptionData.value = res.data.assetTypeList;
  for (let i = 0; i < res.data.assetTypeList.length; i++) {
    let assetType = res.data.assetTypeList[i];
    cellData.value.types[assetType.id] = assetType.name;
  }
}
getAssetType();

/**
 * form表单回显信息
 */
const initFormData = async (id) => {
  const res = await request.get("/asset/" + id);
  form.value = res.data.asset;
}

/**
 * 多条数据的表格信息
 */
const tableData = ref([]);

/**
 * 初始化表格数据
 */
const initTableData = async (array) => {
  const res = await request.post("/asset/listById", array);
  console.log(res.data.assetList);
  tableData.value = res.data.assetList;
}

/**
 * 单元格数据
 */
const cellData = ref({
  editProp: ['zcmc', 'typeId', 'zcxh', 'sccj', 'kcsl'],
  clickCellMap: {},
  types: {},
})

/**
 * 格式化
 */
const formatTypeId = (val) => {
  return cellData.value.types[val];
}

/**
 * 点击cell
 */
const handleCellClick = (row, column, cell, event) => {
  const property = column.property
  //点击单元格的prop属性与已经定义好的数组值匹配
  if (cellData.value.editProp.includes(property)) {
    // 保存cell
    saveCellClick(row, cell)
    cell.querySelector('.item_txt').style.display = 'none'
    cell.querySelector('.item_input').style.display = 'block'
    cell.querySelector('input').focus()
  }
}

/**
 * 取消编辑状态
 */
const cancelEditable = (cell) => {
  cell.querySelector('.item_txt').style.display = 'block'
  cell.querySelector('.item_input').style.display = 'none'
}

/**
 * 保存进入编辑的cell
 */
const saveCellClick = (row, cell) => {
  const id = row.id
  if (cellData.value.clickCellMap[id] !== undefined) {
    if (!cellData.value.clickCellMap[id].includes(cell)) {
      cellData.value.clickCellMap[id].push(cell)
    }
  } else {
    cellData.value.clickCellMap[id] = [cell]
  }
}

/**
 * 保存修改的内容
 */
const save = (row) => {
  const id = row.id
  if (cellData.value.clickCellMap[id] === undefined) {
    ElMessage.error("未编辑，保存失败")
  } else {
    // 取消本行所有cell的编辑状态
    cellData.value.clickCellMap[id].forEach((cell) => {
      cancelEditable(cell)
    })
  }
  cellData.value.clickCellMap[id] = [];
}

/**
 * 向父组件抛方法
 */
const emits = defineEmits(['update:modelValue', 'initAssetList', 'resetAssetIds'])

/**
 * 手动关闭对话框
 */
const handleClose = () => {
  emits('update:modelValue', false);
  emits('resetAssetIds');
  multiSelectData.value.id = -1;
  multiSelectData.value.idsArray = [];
  multiSelectData.value.singleMulti = false;
  cellData.value.clickCellMap = {};
}

const formRef = ref(null)

/**
 * 提交方法
 */
const handleConfirm = async () => {
  if (multiSelectData.value.idsArray.length > 1) {
    const res = await request.post("asset/batchSave", tableData.value);
    if (res.data.code === 200) {
      ElMessage.success("执行成功")
      emits("initAssetList")
      handleClose();
    }
  } else {
    formRef.value.validate(async (valid) => {
      if (valid) {
        const res = await request.post("asset/save", form.value);
        if (res.data.code === 200) {
          ElMessage.success("执行成功")
          formRef.value.resetFields();
          emits("initAssetList")
          handleClose();
        } else {
          ElMessage.error(res.data.msg);
        }
      } else {
        ElMessage.error("系统故障，请联系维护");
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.item_input {
  display: none;
  font-size: 13px;
}

.item_txt {
  display: block;
}

::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 15px;
}
</style>